import { Component, OnInit, ViewChildren, QueryList } from '@angular/core';
import { TableStyle, TablestyleService } from 'src/app/service/business/tablestyle.service';
import { PrimeNgTableCol, ZorroOption, JsonResult } from 'src/app/global/model';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { NextTabDirective } from 'src/app/global/custom-directive/next-tab.directive';
import { MessageService } from 'primeng/api';
import { ArrayUtilsService } from 'src/app/service/common/array-utils.service';
import { ContactTypeService, ContactType } from 'src/app/service/business/contact-type.service';
import { ContactCompanyService, ContactCompany } from 'src/app/service/business/contact-company.service';


@Component({
  selector: 'app-contact-company',
  templateUrl: './contact-company.component.html',
  styleUrls: ['./contact-company.component.css'],
  providers: [ MessageService ]
})
export class ContactCompanyComponent implements OnInit {


  // 复制时需要修改的变量
  dataTableName:string = 'contact_company';

  primeNgTableCols:PrimeNgTableCol[] = [];
  selectedColumns:PrimeNgTableCol[] = [];

  oriData:ContactCompany[] = [];
  tableData:ContactCompany[] = [];
  selectedRow:ContactCompany = null;
  

  editForm:FormGroup;
  drawerVisible:boolean = false;
  // right、left、top、bottom
  drawerPlacement:string = 'right';

  // horizontal、vertical、inline
  formLayout:string = 'horizontal';

  zMultiSelectorOptions:ZorroOption[] = [];
  zMultiSelecteds:string[] = [];

  zOpts_ContactType:ZorroOption[] = [];
  zMultiSelecteds_ContactType:string[] = [];

  @ViewChildren(NextTabDirective) inputs: QueryList<NextTabDirective>;

  searchValue:string = '';

  constructor(
    private styleService:TablestyleService,
    private msgService:MessageService,
    private fb:FormBuilder,
    private arrService:ArrayUtilsService,
    private dataService:ContactCompanyService,
    private contactType:ContactTypeService
  ) { 
    this.msg('进入了constructor');
    this.init();
  }

  ngOnInit() {
    this.initForm();
  }

  ngAfterViewInit(): void {
    this.initTab();
  }

  initTab(){
    const controls=this.inputs.toArray();
    for (let i=0;i<controls.length-1;i++){
      controls[i].nextControl=controls[i+1].self;
    }
  }


  closeDrawer(){
    this.drawerVisible = false;
  }

  // 编辑数据
  edit(){
    if( this.selectedRow === null ) {
      this.msg('没有选中行！');
      return
    }

    this.editForm.patchValue({...this.selectedRow});
    this.drawerVisible = true;
  }

  // 删除选中行
  delete(){
    if( this.selectedRow === null ) {
      this.msg('没有选中行！');
      return
    }

    let sid:string = this.selectedRow.sid;
    this.dataService.deleteByPrimaryKey(sid).subscribe(
      ( res:JsonResult ) => {
        if( res.code !== 1 ){
          this.msg('删除行失败！');
        }else{
          this.msg('删除成功！');
          // 删除数组中的数据
          this.tableData = this.tableData.filter(
            ( item:ContactCompany) => {
              return item.sid !== sid;
            }
          )
        }
          
      },error => console.log('删除行时出错！')
    )
  }

  cancelDelete(){

  }

  cancelEdit(){
    this.drawerVisible = false;
  }

  saveEdit(){
    this.drawerVisible = false;
    this.dataService.saveOne({...this.editForm.value}).subscribe(
      ( res:JsonResult ) => {
        console.log(res);
        if( res.code !== 1 ){
          this.msg(res.msg);
        }else{
          this.msg('保存成功！');
          this.refreshTableData();
        }

      },error => console.log('保存的异步请求出错了')
    )

  }

  // 新增一行数据
  addNew(){
    this.initForm();
    this.drawerVisible = true;
  }


  // 初始化编辑用表单
  initForm(){
    this.editForm = this.fb.group({
      iid:[null],
      sid:[null,Validators.required],
      name:[null,Validators.required],
      typeSidArray:[null,Validators.required],
      alias:[null]
    })
  }

  refreshTableData(){
    this.dataService.selectAll().subscribe(
      ( res:JsonResult ) => {
        if( res.code !==1 ) {
          this.msg('获取表格数据时出错！');
          return
        }

        this.tableData = res.data;
        this.oriData = res.data;
      },error => console.log('获取表数据时出错')
    )
  }

  initOpts(){
    // 初始化往来单位类型下拉的数据
    this.contactType.all2ZOptions().subscribe(
      ( res:ZorroOption[] ) =>{
        this.zOpts_ContactType = res;
      },error => console.log('获取往来单位类型数组时出错！')
    )
  }


  init(){
    // 初始化下拉数据
    this.initOpts();

    // 初始化编辑用表单
    this.initForm();

    // 构建表格列对象数组
    this.styleService.selectTable(this.dataTableName).subscribe(
      ( res:JsonResult ) => {
        this.primeNgTableCols = this.styleService.toPrimeNgTableCols(res.data);
        this.selectedColumns = this.primeNgTableCols;
        this.zMultiSelectorOptions = this.styleService.toZorroOptions(res.data);
        this.zMultiSelectorOptions.forEach(ele => {
          this.zMultiSelecteds.push(ele.value);
        });
      },error => console.log('获取表'+ this.dataTableName +'配置时出错！')
    )

    // 构建表格数据数组
    this.refreshTableData();
  }


  // 列显示选择器如果使用 PrimeNG 的 MultiSelect 则不需要本方法
  // 使用了 zorro 的下拉多选，需要将控件中绑定的变量转换为 PrimeNG Table
  // 可以识别的列对象数组
  zorroSelected2PrimeNgSelectedCols(){
    if( this.zMultiSelecteds === undefined || this.zMultiSelecteds === null 
      || this.zMultiSelecteds.length<=0) return

    this.selectedColumns = [];
    this.selectedColumns = this.arrService.getSames2(this.primeNgTableCols,this.zMultiSelecteds,'field');
  }


  msg(content:string) {
    this.msgService.add({key: 'custom', severity:'info', summary: '通知', detail:content});
  }

  searchChange(){
    if ( this.searchValue.length <=0 )
      this.tableData = this.oriData;
  }

  search(e){
    if( this.tableData === null || this.tableData.length<=0 ) return
    if( this.searchValue.length <=0 ) return
    
    this.tableData = this.tableData.filter(
      ( item:ContactCompany ) => {
        for(let attr in item){
          let strValue = item[attr] + '';
          strValue = strValue.toLowerCase();
          this.searchValue = this.searchValue.toLowerCase();
          let index = strValue.indexOf(this.searchValue);
          if( index >=0 ) return item;
        }
      }
    )
    
  }
}
